package com.jkhan.demo.reflect;

import org.junit.Test;

import java.util.Random;

/**
 * @ClassName NewInstanceTest
 * @Description NewInstanceTest
 * @Author hjk
 * @Date 2022/2/27 21:38
 **/
public class NewInstanceTest {

    @Test
    public void test1() throws IllegalAccessException, InstantiationException {
        Class<Person> clazz = Person.class;

        Person person = clazz.newInstance();
        System.out.println(person);
    }

    @Test
    public void test2() {

        for (int i = 0; i < 100; i++) {
            String classPath = "";
            int num = new Random().nextInt(3);
            switch (num) {
                case 0:
                    classPath = "java.util.Date";
                    break;
                case 1:
                    classPath = "java.lang.Object";
                    break;
                case 2:
                    classPath = "com.jkhan.demo.reflect.Person";
                    break;
            }
            try {
                Object object = getInstance(classPath);
                System.out.println(object);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Object getInstance(String classPath) throws Exception {
        Class clazz = Class.forName(classPath);
        return clazz.newInstance();
    }
}
